package cn.hyatt.auth.listener;

import cn.hyatt.auth.entity.SystemUser;
import cn.hyatt.auth.event.AuthEvent;
import cn.hyatt.auth.service.AuthCacheService;
import cn.hyatt.auth.service.AuthService;
import cn.hyatt.auth.service.SystemUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 身份验证事件侦听器
 *
 * @author hyatt
 */
@Slf4j
@Component
@AllArgsConstructor
public class AuthEventListener {
    private AuthService authService;
    private AuthCacheService authCacheService;
    private SystemUserService systemUserService;


    /**
     * 登录成功事件监听器
     *
     * @param event 登录成功事件
     */
    @EventListener
    public void loginSuccess(AuthEvent.LoginSuccess event) {
        Optional<SystemUser> opt = systemUserService.getOptById(event.getLoginUserId());
        opt.ifPresent(it -> {
            // 保存用户信息至缓存
            systemUserService.saveCache(systemUserService.toVo(it));
            // 保存用户Token信息
            authCacheService.saveAuthInfo(event.getLoginUserId(), event.getAuthInfo());
        });
    }

    /**
     * 刷新Token事件监听器
     *
     * @param event 登录成功事件
     */
    @EventListener
    public void loginSuccess(AuthEvent.FlushedToken event) {
        Optional<SystemUser> opt = systemUserService.getOptById(event.getLoginUserId());
        opt.ifPresent(it -> {
            // 保存用户信息至缓存
            systemUserService.saveCache(systemUserService.toVo(it));
            // 保存用户Token信息
            authCacheService.saveAuthInfo(event.getLoginUserId(), event.getAuthInfo());
        });
    }
}
